﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GtaAPIClient.XhDoOrderService;
using GtaAPIClient.XhDoQueryService;
using GtaAPIClient.CounterComprehensiveService;
using zbus;

namespace GtaAPIClient
{
    class XhManage
    {
        WcfService wcfService = null; 
        ServiceConsole.UpdateTextDelegate delg = null;

        public XhManage()
        {
            wcfService = new WcfServiceImpl();
        }

        public XhManage(ServiceConsole.UpdateTextDelegate delg)
        {
            this.delg = delg;
            delg.BeginInvoke("XhManage服务初始化成功", null, null);
            wcfService = new WcfServiceImpl();
        }

        public void test()
        { 
            getTodayOrder("10248", "xiZPpGGQNf8=", 100, 1);
            //getHistoryOrder("010001024802", "xiZPpGGQNf8=", 100, 1);
            //getXhTodayTrade("010001030702", "PTkhYU4x1jM=", 100, 1);
            //getXhAccountHoldDetail("010001030702", "PTkhYU4x1jM=", 100, 1);
            //getMaxOrderAmount("10307", 10.0f, "600000",1);
            //getAssetsSummary("10307", "PTkhYU4x1jM=");
            //getSpotCapital("010001030702", "PTkhYU4x1jM=");
            //getStockQuotation("600000,600005,600009", 1);
            getMaxSellAmount("010001024802", "xiZPpGGQNf8=", "002003");
        }

        [Remote("getStockQuotation")]
        public StockQuotationResult getStockQuotation(string codeStr, int breedClassType)
        {
            try
            {
                StockQuotationResult res = new StockQuotationResult();
                string errMsg = "";

                if (string.IsNullOrEmpty(codeStr))
                {
                    res.IsSuccess = false;
                    res.Message = "证券代码不能为空";
                    return res;
                }

                string[] codes = codeStr.Split(',');

                List<MarketDataLevel> hqList = new List<MarketDataLevel>();
                foreach (string code in codes)
                {
                    MarketDataLevel hq = wcfService.getStockQuotation(out errMsg, code, breedClassType);
                    if (!string.IsNullOrEmpty(errMsg))
                    {
                        res.IsSuccess = false;
                        res.Message = errMsg;
                        return res;
                    }
                    hqList.Add(hq);
                }
                res.ResultList = hqList;
                res.IsSuccess = true;
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("获取行情失败" + ex.Message, null, null);
                throw new Exception("获取行情失败", ex);
            }
        }


        [Remote("xhDoOrder")]
        public OrderResponse doOrder(string capitalAccount, string stockCode, int buySell, 
                float orderQuty, float orderPrice, int unit, int marketPrice, string PortfoliosId, string traderId, string traderPassword)
        {
            try{
                XhDoOrderService.StockOrderRequest stockOrderReq = new XhDoOrderService.StockOrderRequest();
                stockOrderReq.BuySell = buySell == 1 ? XhDoOrderService.TypesTransactionDirection.Buying : XhDoOrderService.TypesTransactionDirection.Selling;
                stockOrderReq.Code = stockCode;
                stockOrderReq.FundAccountId = capitalAccount;
                stockOrderReq.OrderAmount = orderQuty;
                stockOrderReq.OrderPrice = orderPrice;
                if (stockCode.StartsWith("1") || stockCode.StartsWith("5"))
                {
                    stockOrderReq.OrderUnitType = XhDoOrderService.TypesUnitType.Share;
                }
                else
                {
                    stockOrderReq.OrderUnitType = XhDoOrderService.TypesUnitType.Thigh;
                }
                stockOrderReq.OrderWay = marketPrice == 1 ? XhDoOrderService.GTTypesOrderPriceType.OPTMarketPrice : XhDoOrderService.GTTypesOrderPriceType.OPTLimited;
                stockOrderReq.PortfoliosId = PortfoliosId;
                stockOrderReq.TraderId = traderId;
                stockOrderReq.TraderPassword = traderPassword;
            
                OrderResponse orderRes = wcfService.doOrder(stockOrderReq);
                return orderRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货委托失败" + ex.Message, null, null);
                throw new Exception("现货委托失败", ex);
            }
        }


        [Remote("xhCancelOrder")]
        public CancelOrderResult cancelOrder(string orderId)
        {
            try
            {
                GTTypesOrderStateType ost = new GTTypesOrderStateType();
                string message = "";
                bool isSuccess = wcfService.cancelOrder(orderId, ref message, out ost);
                CancelOrderResult xhCancelReturnMsg = new CancelOrderResult();
                xhCancelReturnMsg.IsSucess = isSuccess;
                xhCancelReturnMsg.Message = message;
                xhCancelReturnMsg.OrderStatus = (int)ost;
                return xhCancelReturnMsg;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货委托撤单失败" + ex.Message, null, null);
                throw new Exception("现货委托撤单失败", ex);
            }
        }

        [Remote("xhGetMaxOrderAmount")]
        public int getMaxOrderAmount(string TraderId, float OrderPrice, string Code, int marketPrice)
        {
            try
            {
                string outMessage = "";
                CounterComprehensiveService.GTTypesOrderPriceType orderPriceType = marketPrice == 1 ?
                    CounterComprehensiveService.GTTypesOrderPriceType.OPTMarketPrice : CounterComprehensiveService.GTTypesOrderPriceType.OPTLimited;
                long res = wcfService.getMaxOrderAmount(out outMessage, TraderId, OrderPrice, Code, orderPriceType);
                return ((int)res/100)*100;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货获取最大委托数量失败" + ex.Message, null, null);
                throw new Exception("现货获取最大委托数量失败", ex);
            }
        }

        [Remote("xhGetMaxSellAmount")]
        public int getMaxSellAmount(string capitalAccount, string strPassword, string stockCode)
        {
            SpotHoldConditionFindEntity cond = new SpotHoldConditionFindEntity();
            cond.SpotCode = stockCode;
            
            int count = 0;
            int start = 1;
            int pageLength = 100;
            string strErrorMessage = "";

            try
            {
                decimal max = 0;
                SpotHoldFindResultEntity[] res = wcfService.queryHold(out count, capitalAccount, strPassword, cond, start, pageLength, ref strErrorMessage);
                if (res == null || res.Length <= 0)
                { 
                    return 0;
                }
                foreach (SpotHoldFindResultEntity r in res)
                {
                    if (r.HoldFindResult != null)
                    {
                        max += r.HoldFindResult.AvailableAmount;
                    }
                }
                return (int)max;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货查询持仓详细信息失败" + ex.Message, null, null);
                throw new Exception("现货查询持仓详细信息失败", ex);
            }
        }

        /* 国泰安中该方法有错误
       [Remote("xhGetTodayOrder")]
       public TodayEntrustResult getTodayOrder(string capitalAccount, string pwd, int pageSize, int pageNo)
       {
           int total = 0;
           string errorMsg = "";
           SpotEntrustConditionFindEntity cond = new SpotEntrustConditionFindEntity();
           //cond.BelongToMarket = 1;
           //cond.CurrencyType = 1; 
           //cond.SpotCapitalAccount = capitalAccount;  
           cond.SpotCode = "";
           try
           {
               TodayEntrustResult pagingRes = new TodayEntrustResult();
               XH_TodayEntrustTableInfo[] res = wcfService.queryOrder(out total, capitalAccount, pwd, cond, pageNo, pageSize, ref errorMsg);
               if (res == null || res.Length <= 0)
               {
                   pagingRes.Total = 0;
                   pagingRes.Message = errorMsg;
                   return pagingRes;
               }
               pagingRes.Total = total;
               TodayEntrust[] tmp = new TodayEntrust[res.Length];
               int i = 0;
               foreach (XH_TodayEntrustTableInfo e in res)
               {
                   TodayEntrust m = new TodayEntrust(); 
                   m.EntrustAmount = e.EntrustAmount;
                   m.EntrustNumber = e.EntrustNumber;
                   m.EntrustPrice = e.EntrustPrice;
                   m.EntrustTime = e.EntrustTime.ToString();
                   m.TradeAmount = e.TradeAmount;
                   m.TradeAveragePrice = e.TradeAveragePrice;
                   m.CancelAmount = e.CancelAmount;
                   m.IsMarketValue = e.IsMarketValue;
                   m.OrderMessage = e.OrderMessage;
                   m.OrderStatusId = e.OrderStatusId;
                   m.BuySellTypeId = e.BuySellTypeId;
                   m.SpotCode = e.SpotCode;
                   m.CancelLogo = e.CancelLogo == true ? 1 : 0; 
                   tmp[i++] = m;
               }
               pagingRes.ResultList = tmp;
               return pagingRes;
           }
           catch (Exception ex)
           {
               delg.BeginInvoke("现货查询当日委托失败" + ex.Message, null, null);
               throw new Exception("现货查询当日委托失败", ex);
           }
       }*/

        [Remote("xhGetTodayOrder")]
        public TodayEntrustResult getTodayOrder(string userID, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMessage = "";
            DoCommonQuery.SpotEntrustConditionFindEntity filter = new DoCommonQuery.SpotEntrustConditionFindEntity();
            
            DoCommonQuery.PagingInfo pageInfo = new DoCommonQuery.PagingInfo();
            pageInfo.CurrentPage = pageNo;
            pageInfo.IsCount = true;
            pageInfo.PageLength = pageSize; 

            try
            {
                TodayEntrustResult pagingRes = new TodayEntrustResult();
                DoCommonQuery.XH_TodayEntrustTableInfo[] res = wcfService.queryOrder(out total, out errorMessage, userID, pwd, 2, filter, pageInfo);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    pagingRes.Message = errorMessage;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayEntrust[] tmp = new TodayEntrust[res.Length];
                int i = 0;
                foreach (DoCommonQuery.XH_TodayEntrustTableInfo e in res)
                {
                    TodayEntrust m = new TodayEntrust();
                    m.EntrustAmount = e.EntrustAmount;
                    m.EntrustNumber = e.EntrustNumber;
                    m.EntrustPrice = e.EntrustPrice;
                    m.EntrustTime = e.EntrustTime.ToString();
                    m.TradeAmount = e.TradeAmount;
                    m.TradeAveragePrice = e.TradeAveragePrice;
                    m.CancelAmount = e.CancelAmount;
                    m.IsMarketValue = e.IsMarketValue;
                    m.OrderMessage = e.OrderMessage;
                    m.OrderStatusId = e.OrderStatusId;
                    m.BuySellTypeId = e.BuySellTypeId;
                    m.SpotCode = e.SpotCode;
                    m.CancelLogo = e.CancelLogo == true ? 1 : 0;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货查询当日委托失败" + ex.Message, null, null);
                throw new Exception("现货查询当日委托失败", ex);
            }
        }

        [Remote("xhGetHistoryOrder")]
        public TodayEntrustResult getHistoryOrder(string capitalAccount, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            SpotEntrustConditionFindEntity cond = new SpotEntrustConditionFindEntity();
            try
            {
                TodayEntrustResult pagingRes = new TodayEntrustResult();
                XH_HistoryEntrustTableInfo[] res = wcfService.queryHistoryOrder(out total, out errorMsg, capitalAccount, pwd, pageNo, pageSize, cond);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    pagingRes.Message = errorMsg;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayEntrust[] tmp = new TodayEntrust[res.Length];
                int i = 0;
                foreach (XH_HistoryEntrustTableInfo e in res)
                {
                    TodayEntrust m = new TodayEntrust();
                    m.EntrustAmount = e.EntrustMount;
                    m.EntrustNumber = e.EntrustNumber;
                    m.EntrustPrice = e.EntrustPrice;
                    m.EntrustTime = e.EntrustTime.ToString();
                    m.TradeAmount = e.TradeAmount;
                    m.TradeAveragePrice = e.TradeAveragePrice;
                    m.CancelAmount = e.CancelAmount;
                    m.IsMarketValue = e.IsMarketValue;
                    m.OrderMessage = e.OrderMessage;
                    m.OrderStatusId = e.OrderStatusId;
                    m.BuySellTypeId = e.BuySellTypeId;
                    m.SpotCode = e.SpotCode;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货查询历史委托失败" + ex.Message, null, null);
                throw new Exception("现货查询历史委托失败", ex);
            }
        }

        [Remote("xhGetTodayTrade")]
        public TodayTradeResult getTodayTrade(string capitalAccount, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            SpotTradeConditionFindEntity cond = new SpotTradeConditionFindEntity();
            cond.TradeType = 1;
            try
            {
                TodayTradeResult pagingRes = new TodayTradeResult();
                XH_TodayTradeTableInfo[] res = wcfService.queryTrade(out total, out errorMsg, capitalAccount, pwd, pageNo, pageSize, cond);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    pagingRes.Message = errorMsg;
                    return pagingRes;
                }
                pagingRes.Total = total;
                TodayTrade[] tmp = new TodayTrade[res.Length];
                int i = 0;
                foreach (XH_TodayTradeTableInfo e in res)
                {
                    TodayTrade m = new TodayTrade();
                    m.SpotCode = e.SpotCode;
                    m.TradeTime = e.TradeTime.ToString();
                    m.TradePrice = e.TradePrice;
                    m.TradeAmount = e.TradeAmount;
                    m.TradeCapitalAmount = e.TradeCapitalAmount;
                    m.Commission = e.Commission;
                    m.StampTax = e.StampTax;
                    m.ClearingFee = e.ClearingFee;
                    m.MonitoringFee = e.MonitoringFee;
                    m.TradeProceduresFee = e.TradeProceduresFee;
                    m.TransferAccountFee = e.TransferAccountFee;
                    m.TradingSystemUseFee = e.TradingSystemUseFee;
                    m.TradeTypeId = e.TradeTypeId;
                    m.BuySellTypeId = e.BuySellTypeId;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货查询当日成交失败" + ex.Message, null, null);
                throw new Exception("现货查询当日成交失败", ex);
            }
        }

        [Remote("xhGetHistoryTrade")]
        public TodayTradeResult getHistoryTrade(string capitalAccount, string pwd, int pageSize, int pageNo)
        {
            int total = 0;
            string errorMsg = "";
            SpotTradeConditionFindEntity cond = new SpotTradeConditionFindEntity();
            cond.TradeType = 1;
            try
            {
                TodayTradeResult pagingRes = new TodayTradeResult();
                XH_HistoryTradeTableInfo[] res = wcfService.queryHistoryTrade(out total, out errorMsg, capitalAccount, pwd, pageNo, pageSize, cond);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    pagingRes.Message = errorMsg;
                    return pagingRes;
                } 
                pagingRes.Total = total;
                TodayTrade[] tmp = new TodayTrade[res.Length];
                int i = 0;
                foreach (XH_HistoryTradeTableInfo e in res)
                {
                    TodayTrade m = new TodayTrade();
                    m.SpotCode = e.SpotCode;
                    m.TradeTime = e.TradeTime.ToString();
                    m.TradePrice = e.TradePrice;
                    m.TradeAmount = e.TradeAmount;
                    m.TradeCapitalAmount = e.TradeCapitalAmount;
                    m.Commission = e.Commission;
                    m.StampTax = e.StampTax;
                    m.ClearingFee = e.ClearingFee;
                    m.MonitoringFee = e.MonitoringFee;
                    m.TradeProceduresFee = e.TradeProceduresFee;
                    m.TransferAccountFee = e.TransferAccountFee;
                    m.TradingSystemUseFee = e.TradingSystemUseFee;
                    m.TradeTypeId = e.TradeTypeId;
                    m.BuySellTypeId = e.BuySellTypeId;
                    tmp[i++] = m;
                }
                pagingRes.ResultList = tmp;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货查询历史成交失败" + ex.Message, null, null);
                throw new Exception("现货查询历史成交失败", ex);
            }
        }

        [Remote("xhGetAccountHoldDetail")]
        public XhHoldResult getAccountHoldDetail(string capitalAccount, string strPassword, string stockCode, int pageSize, int pageNo)
        {
            SpotHoldConditionFindEntity cond = new SpotHoldConditionFindEntity();
            if (!string.IsNullOrEmpty(stockCode))
            {
                cond.SpotCode = stockCode;
            }
            int count = 0;
            int start = pageNo;
            int pageLength = pageSize;
            string strErrorMessage = "";

            try
            {
                XhHoldResult pagingRes = new XhHoldResult();
                SpotHoldFindResultEntity[] res = wcfService.queryHold(out count, capitalAccount, strPassword, cond, pageNo, pageSize, ref strErrorMessage);
                if (res == null || res.Length <= 0)
                {
                    pagingRes.Total = 0;
                    return pagingRes;
                }
                
                pagingRes.Total = count;
                pagingRes.ResultList = res;
                return pagingRes;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货查询持仓详细信息失败" + ex.Message, null, null);
                throw new Exception("现货查询持仓详细信息失败", ex);
            }
        }

        [Remote("xhGetCapital")]
        public XhDoQueryService.SpotCapitalEntity getSpotCapital(string strFundAccountId, string userPassword)
        {
            try
            { 
                string strErrorMessage = "";
                XhDoQueryService.SpotCapitalEntity res = wcfService.getSpotCapital(strFundAccountId, XhDoQueryService.TypesCurrencyType.RMB, userPassword, ref strErrorMessage);
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("现货查询资产信息失败" + ex.Message, null, null);
                throw new Exception("现货查询资产信息失败", ex);
            }
        }

        /// <summary>
        /// 查询用户总资产信息，目前还未用到
        /// </summary>
        /// <param name="traderId"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public XhDoQueryService.AssetSummaryEntity[] getAssetsSummary(string traderId, string password)
        {
            try
            {
                string outMessage = "";
                XhDoQueryService.AssetSummaryEntity[] res = wcfService.getAssetsSummary(out outMessage, traderId, password);
                return res;
            }
            catch (Exception ex)
            {
                delg.BeginInvoke("查询用户总资产信息失败" + ex.Message, null, null);
                throw new Exception("查询用户总资产信息失败", ex);
            }
        }

    }


    class CancelOrderResult
    {
        public bool IsSucess { get; set;}

        public string Message { get; set; }

        public int OrderStatus { get; set; } 
    }

    class TodayEntrustResult
    {
        public int Total { get; set; }

        public string Message { get; set; }

        public TodayEntrust[] ResultList { get; set; }
    }

    class TodayEntrust
    {  
        public string SpotCode { get; set; }
        public int BuySellTypeId { get; set; }
        public decimal EntrustPrice { get; set; }
        public decimal EntrustAmount { get; set; }
        public bool IsMarketValue { get; set; }
        public int OrderStatusId { get; set; }
        public string EntrustTime { get; set; }
        public string OrderMessage { get; set; }
        public string EntrustNumber { get; set; }
        public decimal TradeAmount { get; set; }
        public decimal CancelAmount { get; set; } 
        public decimal TradeAveragePrice { get; set; } 
        public decimal CloseFloatProfitLoss { get; set; }
        public decimal CloseMarketProfitLoss { get; set; }
        public int OpenCloseTypeId { get; set; }
        public int CancelLogo { get; set; }
    }

    class TodayTradeResult
    {
        public int Total { get; set; }

        public string Message { get; set; }

        public TodayTrade[] ResultList { get; set; }
    }

    class TodayTrade
    {
        public string SpotCode { get; set; } 
        public string TradeTime { get; set; }
        public decimal TradePrice { get; set; } 
        public decimal TradeAmount { get; set; }
        public decimal TradeCapitalAmount { get; set; }    
        public decimal Commission { get; set; }  
        public decimal StampTax { get; set; }  
        public decimal ClearingFee { get; set; }  
        public decimal MonitoringFee { get; set; }  
        public decimal TradeProceduresFee { get; set; }  
        public decimal TransferAccountFee { get; set; }  
        public decimal TradingSystemUseFee { get; set; }
        public decimal MarketProfitLoss { get; set; }
        public int OpenCloseTypeId { get; set; }
        public int TradeTypeId { get; set; }
        public int BuySellTypeId { get; set; }
        public int OrderType { get; set; }
    }

    class XhHoldResult
    {
        public int Total { get; set; }

        public SpotHoldFindResultEntity[] ResultList { get; set; }
    }

    class StockQuotationResult
    {
        public bool IsSuccess { get; set; }

        public string Message { get; set; }

        public List<MarketDataLevel> ResultList { get; set; }
    }

}
